package juc.threadpool;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledThreadPoolExecutorDemo {

    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
        Task task = new Task("任务");
        //executorService.schedule(task,2, TimeUnit.SECONDS);//只执行一次
        //executorService.scheduleWithFixedDelay(task,0,2,TimeUnit.SECONDS);//任务加延迟--period为负数
        executorService.scheduleAtFixedRate(task,0,1,TimeUnit.SECONDS);//任务延迟取最大值 稳定定时器

    }

}

@Data
@AllArgsConstructor
class Task implements Runnable{

    String name;

    @Override
    public void run() {
        System.out.println("Executing :"+name+",Current Seconds:"+new Date().getSeconds());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
